package com.example.guiguiapplicatio.api;

import android.os.NetworkOnMainThreadException;
import android.util.Log;

import androidx.fragment.app.Fragment;
import com.example.guiguiapplicatio.api.Interface.SearchRecordCallback;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.example.guiguiapplicatio.Response.Record;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.example.guiguiapplicatio.api.GetCountTotalApi.ip;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SearchRecordApi {
    private final Gson gson = new Gson();
    private SearchRecordCallback searchRecordCallback;
    private Fragment fragment;
    public SearchRecordApi(Fragment fragment) {
        this.fragment = fragment;
    }
    public void setSearchRecordCallback(SearchRecordCallback searchRecordCallback) {this.searchRecordCallback = searchRecordCallback;
    }
    public void performSearchRecordList(Integer status,String sex,Integer age,String idNamePhone,List<String> listenername) {
        new Thread(() -> {
            String url = "http://"+ip +":9090/recordsearch";
            //  请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
//                    .add("appId", "用户所申请的应用ID")
//                    .add("appSecret", "用户所申请的应用密钥")
                    .add("Content-Type", "application/json")
                    .build();
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("status", status);
            bodyMap.put("sex", sex);
            bodyMap.put("age", age);
            bodyMap.put("idNamePhone", idNamePhone);
            bodyMap.put("listenername", listenername);
            String body=gson.toJson(bodyMap);
            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                client.newCall(request).enqueue(callback);
            } catch (NetworkOnMainThreadException ex) {
                ex.printStackTrace();
            }
        }).start();
    }
    private final Callback callback=new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            if(searchRecordCallback!=null){
                searchRecordCallback.onSearchFailure(e.getMessage());
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                if (response.isSuccessful()) {
                    Type jsonType = new TypeToken<ResponseBody<List<Record>>>() {}.getType();
                    String body = response.body().string();
                    Log.d("info", body);
                    ResponseBody<List<Record>> dataResponseBody = gson.fromJson(body, jsonType);
                    Log.d("info", String.valueOf(dataResponseBody));
                    if (searchRecordCallback != null) {
                        fragment.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                searchRecordCallback.onSearchSuccess(dataResponseBody);
                            }
                        });
                    }
                } else {
                    if (searchRecordCallback != null) {
                        searchRecordCallback.onSearchFailure("Response was not successful: " + response.code());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (searchRecordCallback != null) {
                    searchRecordCallback.onSearchFailure(e.getMessage());
                }
            }
        }
    };

}
